﻿
namespace EasyNet.Solr.Impl
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;

    public class XmlFacetRangesParser : ISolrResponseParser<string, IDictionary<string, FacetRange>>
    {
        #region ISolrResponseParser<string,IDictionary<string,FacetRange>> Members

        public IDictionary<string, FacetRange> Parse(string result)
        {
            if (string.IsNullOrEmpty(result))
            {
                return null;
            }

            var xmlDoc = XDocument.Parse(result);

            var facetCounts = from e in xmlDoc.Root.Elements("lst")
                              where (string)e.Attribute("name") == "facet_counts"
                              select e;

            if (facetCounts == null)
            {
                return null;
            }

            var facetRanges = from e in facetCounts.Elements("lst")
                              where (string)e.Attribute("name") == "facet_ranges"
                              select e;

            if (facetRanges == null)
            {
                return null;
            }

            var facetRangesResult = new Dictionary<string, FacetRange>(facetRanges.Single().Elements().Count());

            foreach (var element in facetRanges.Single().Elements())
            {
                var fieldName = element.Attribute("name").Value;

                if (!facetRangesResult.ContainsKey(fieldName))
                {
                    facetRangesResult.Add(fieldName, new FacetRange() { Start = from e in element.Elements() where (string)e.Attribute("name") == "start" select e.Value, End = from e in element.Elements() where (string)e.Attribute("name") == "end" select e.Value, Gap = from e in element.Elements() where (string)e.Attribute("name") == "gap" select e.Value });
                }

                var countsElement = from e in element.Elements()
                                    where (string)e.Attribute("name") == "counts"
                                    select e;

                if (countsElement != null)
                {
                    facetRangesResult[fieldName].Counts = new List<FacetField>(countsElement.Elements().Count());

                    foreach (var facetFieldEl in countsElement.Elements())
                    {
                        facetRangesResult[fieldName].Counts.Add(new FacetField() { Name = facetFieldEl.Attribute("name").Value, Count = int.Parse(facetFieldEl.Value) });
                    }
                }
            }

            return facetRangesResult;
        }

        #endregion
    }
}
